<template>
  <!--新增绩效部门弹窗-->
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="新增绩效部门"
    @visible-change="changeModalVisible"
    @ok="handleSubmit"
    :width="1150"
    :defaultFullscreen="true"
  >
    <BasicForm @register="registerForm" style="padding: 0 24px" />
    <Transfer ref="transferRef" :tree-data="treeData" :rightTreeData="rightTreeData" v-if="show" :parentId="parentId" :edit-key="targetKeys" />
  </BasicModal>
</template>
<script setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import Transfer from '../../../components/treeTransfer/components/composition-transfer.vue';
  import { getDeptTree, createUnit, getUnitTree } from './service';
  import { detailForm } from './departmentManage.data';

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const transferRef = ref(null);
  const [registerForm, { validateFields, resetFields, getFieldsValue, setFieldsValue }] = useForm({
    labelWidth: 100,
    showActionButtonGroup: false,
    schemas: detailForm,
  });
  //表单赋值
  const [registerModal, { closeModal = () => {}, setModalProps = (p) => {} }] = useModalInner(async (data) => {
    console.log('data', data);
    orgCode = data.orgCode;
    targetKeys.value = [];
    let formData = { ...data };
    await setFieldsValue(formData);
    getDeptTree({ parentId: data.suitGroupCode, parentCode: orgCode }).then((res) => {
      try {
        parentId.value = res[0]?.parentId;
        // parentId.value = res[0]?.id;
      } catch (e) {
        console.error(e);
      }
      format(res);
      treeData.value = res;
      show.value = true;
      // 获取列表数据 （列表数据就是右侧数据）
      getUnitTree({ suitUnit: orgCode }).then((res) => {
        rightFormat(res);
        rightTreeData.value = res;
        getAllKeys(res, targetKeys.value); // 获取所有单位的key （orgCode）  targetKeys --> editKey
        console.log('targetKeys.value', targetKeys.value);
        // nextTick(() => {
        //   transferRef.value.onChange(targetKeys.value, 'right');
        // });
      });
    });
  });
  let show = ref(false);
  let treeData = ref([]);
  let rightTreeData = ref([]);
  let parentId = ref('');
  let targetKeys = ref([]);
  let orgCode;
  function format(data) {
    data.forEach((d) => {
      d.title = d.deptName;
      d.id = d.id.toString();
      d.key = d.id + '';
      if (d.children) {
        format(d.children);
      }
    });
  }
  function rightFormat(data) {
    data.forEach((d) => {
      d.title = d.orgName;
      d.id = d.orgCode;
      d.key = d.orgCode;
      if (d.children) {
        rightFormat(d.children);
      }
    });
  }

  function getAllKeys(source, target) {
    source.forEach((s) => {
      target.push(s.deptId + '');
      if (s.children) {
        getAllKeys(s.children, target);
      }
    });
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      // console.log('transferRef.value', transferRef.value);
      // let ids = [];
      // if (transferRef.value.targetKeys) {
      //   transferRef.value.targetKeys.forEach((arg, i) => {
      //     // @ts-ignore
      //     // transferRef.value.targetKeys[i] = parseInt(arg);
      //     ids.push(parseInt(arg));
      //   });
      // }
      setModalProps({ confirmLoading: true });
      if (transferRef.value.emitKeys) {
        transferRef.value.emitKeys.forEach((arg, i) => {
          // @ts-ignore
          transferRef.value.emitKeys[i] = parseInt(arg);
        });
      }
      createUnit({
        ids: transferRef.value.emitKeys,
        orgCode,
      }).then((res) => {
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success', orgCode);
      });
      // await createUnit(transferRef.value.targetKeys);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const changeModalVisible = (visible) => {
    if (!visible) show.value = false;
  };
</script>
